#coding:utf-8

import  datetime
from flask import current_app, g, request, jsonify
from ihome import db, redis_store
from ihome.utils.response_code import RET
from ihome.utils.commons import require_login
from ihome.models import House, Order
from . import  api


@api.route('/order', methods=["POST"])
@require_login
def save_order():
    user_id = g.user_id

    # 获取参数

    order_data = request.get_json()
    if not order_data:
        return jsonify(errno=RET.PARAMERR, errmsg="参数缺失")

    house_id = order_data.get('house_id')
    start_date_str = order_data.get('start_date')
    end_date_str = order_data.get('end_date')

    # 参数检验
    if not all([house_id, start_date_str, end_date_str]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数缺失")
    # 日期格式检查
    try:
        start_date = datetime.datetime.strptime(start_date_str, '%Y-%m-%d')
        end_date = datetime.datetime.strptime(end_date_str, "%Y-%m-%d")
        assert start_date <= end_date
        # 计算预定的天数
        days = (end_date - start_date).days + 1
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="日期格式错误")

    # 查询房屋是否存在
    try:
        house = House.query.get(house_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取房屋失败")
    if not house:
        return jsonify(errno=RET.NODATA, errsmg="房屋不存在")
    # 预定的房子是否是房东自己的
    if user_id == house.user_id:
        return jsonify(errno=RET.ROLEERR, errmsg="不能预定自己的房子")
    # 确保用户预定的时间内，房屋没有被别人下单
    try:
        # 查询冲突的订单数
        count = Order.query.filter(Order.house_id == house_id, Order.begin_date <= end_date,
                                   Order.end_date >= start_date).count()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="检查出错")
    if count > 0:
        return jsonify(errno=RET.DATAERR, errmsg="房屋已被预定")

    # 订单总额
    amount = int(days) * house.price
    print(amount)
    order = Order(
        house_id=house_id,
        user_id=user_id,
        begin_date=start_date,
        end_date=end_date,
        days=days,
        house_price=house.price,
        amount=amount
    )
    try:
        db.session.add(order)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存订单失败")
    return jsonify(errno=RET.OK, errmsg="OK", data={'order_id': order.id, })


@api.route('/user/order', methods=["GET"])
@require_login
def get_user_order():
    user_id = g.user_id
    role = request.args.get('role', '')

    try:
        if role == "landlord":
            # 以房东的身份查询订单
            # 先查询属于自己的房子有哪些
            houses = House.query.filter(House.user_id==user_id).all()
            house_ids = [house.id for house in houses]
            # 在查询预定了自己房子的订单
            orders = Order.query.filter(Order.house_id.in_(house_ids)).order_by(Order.create_time.desc()).all()
        else:
            orders = Order.query.filter(Order.user_id==user_id).order_by(Order.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")
    # 将订单转化为字典数据
    orders_dict_list = []
    if orders:
        for order in orders:
            orders_dict_list.append(order.to_dict())

    return jsonify(errno=RET.OK, errmsg="OK", data={'orders': orders_dict_list})


@api.route('/order/<int:order_id>/status', methods=["PUT"])
@require_login
def accept_reject_order(order_id):
    """接单，拒单"""
    user_id = g.user_id
    # 获取参数
    req_data = request.get_json()
    if not req_data:
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    action = req_data.get('action')
    if action not in ('accept', 'reject'):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
    try:
        # 根据订单号查询订单， 并且要求订单处于等待接单状态
        order = Order.query.filter(Order.id==order_id, Order.status=='WAIT_ACCEPT').first()
        house = order.house
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="无法获取订单数据")
    # 确保房东只能修改自己房子的订单
    if not order or house.user_id != user_id:
        return jsonify(errno=RET.REQERR, errmsg="操作无效")
    if action == 'accept':
        order.status = 'WAIT_PAYMENT'
    elif action == 'reject':
        reason = req_data.get('reason')
        if not reason:
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
        order.status = 'REJECTED'
        order.comment = reason
    try:
        db.session.add(order)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="操作失败")
    return jsonify(errno=RET.OK, errmsg="OK")


@api.route('/order/<int:order_id>/comment', methods=["PUT"])
@require_login
def save_order_comment(order_id):
    """保存订单评论信息"""
    user_id = g.user_id
    # 获取参数
    req_json = request.get_json()
    comment = req_json.get('comment')

    if not comment:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        # 确保只能评价自己下的订单， 而且订单处于待评价的状态才可以
        order = Order.query.filter(Order.id==order_id, Order.user_id==user_id,
                                   Order.status=='WAIT_COMMENT').first()
        house = order.house
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="无法获取订单数据")

    if not order:
        return jsonify(errno=RET.REQERR, errmsg="操作无效")
    try:
        order.status = 'COMPLETE'
        order.comment = comment
        house.order_count += 1
        db.session.add(order)
        db.session.add(house)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="操作失效")

        # 因为房屋详情中有订单的评价信息，为了让最新的评价信息展示在房屋详情中，所以删除redis中关于本订单房屋的详情缓存
    try:
        redis_store.delete("house_info_%s" % order.house.id)
    except Exception as e:
        current_app.logger.error(e)

    return jsonify(errno=RET.OK, errmsg="OK")